package com.xja.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xja.exception.CustomException;
import com.xja.model.entity.User;
import com.xja.model.vo.resp.Result;
import com.xja.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author 蔡建国
 */
@RestController
@RequestMapping("/admin/user")
@Slf4j
@Tag(name = "用户管理")
@RequiredArgsConstructor
public class AdminUserController {

    private final IUserService userService;

    @GetMapping("/list")
    @Operation(summary = "获取用户列表")
    public Result<Page<User>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String nickname
    ) {
        log.info("获取用户列表, page: {}, size: {}, nickname: {}", page, size, nickname);

        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(nickname)) {
            queryWrapper.like(User::getNickname, nickname);
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(User::getCreateTime);

        // 分页查询
        Page<User> pageParam = new Page<>(page, size);
        Page<User> pageResult = userService.page(pageParam, queryWrapper);

        return Result.success(pageResult);
    }

    @PutMapping("/state/{id}")
    @Operation(summary = "更新用户状态")
    public Result<Void> updateState(
            @PathVariable Long id,
            @RequestBody Map<String, Integer> param
    ) {
        log.info("更新用户状态, id: {}, state: {}", id, param.get("state"));

        // 检查用户是否存在
        User user = userService.getById(id);
        if (user == null) {
            throw new CustomException("用户不存在", 400);
        }

        // 更新状态
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setState(param.get("state"));

        boolean success = userService.updateById(updateUser);
        return success ? Result.success() : Result.error("更新失败");
    }
}
